package com.xxx.video.network.responses;


import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.xxx.video.R;
import com.xxx.video.commen.utils.L;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.network.configs.NetWorkConstants;
import com.xxx.video.network.exceptions.NetWorkException;
import com.xxx.video.network.listeners.CommonResponseListener;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class Response2JsonCallback implements Callback {
    /**
     * get a main handler
     */
    private Handler mHandler;
    /**
     * call back
     */
    private CommonResponseListener mCommonResponseListener;
    /**
     * request
     */
    private Request request;

    public Response2JsonCallback(DisposeDataHandle disposeDataHandle, Request request) {
        /*
         * request
         */
        this.request = request;
        /*
         * call back
         */
        this.mCommonResponseListener = disposeDataHandle.mCommonResponseListener;
        /*
         * get a main handler
         */
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onFailure(Call call, final IOException ioException) {
        mHandler.post(() -> {
            L.i("response", "request url\n" + request.url() + "\nresponse\n" + ioException.toString());
            if (mCommonResponseListener != null) {
                mCommonResponseListener.onFailure(new NetWorkException(NetWorkConstants.NetWorkErrorCode.NET_WORK_ERROR, ioException));
            }
        });

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final String responseString = response.body().string();
        L.i("response", "request url\n" + request.url() + "\nresponse\n" + responseString);
        mHandler.post(() -> {
            handlerResponse(responseString);
        });
    }

    /**
     * handler response
     *
     * @param responseString response String
     */
    private void handlerResponse(String responseString) {
        /*
         * if response empty
         */
        if (TextUtils.isEmpty(responseString)) {
            if (mCommonResponseListener != null) {
                mCommonResponseListener.onFailure(new NetWorkException(NetWorkConstants.NetWorkErrorCode.NET_WORK_ERROR, StringUtils.getInstance().getString(R.string.net_work_response_empty)));
            }
            return;
        }
        try {
            Type type = mCommonResponseListener.getClass().getGenericSuperclass();
            Type newType = null;
            if (type instanceof ParameterizedType) {
                Type[] types = ((ParameterizedType) type).getActualTypeArguments();
                newType = types[0];
            }
            if (newType != null) {
                /*
                 * parsing success
                 */
                if (mCommonResponseListener != null) {
                    mCommonResponseListener.onSuccess(new Gson().fromJson(responseString, newType), responseString);
                }
            } else {
                /*
                 * not need parsing
                 */
                if (mCommonResponseListener != null) {
                    mCommonResponseListener.onSuccess(null, responseString);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            /*
             * parsing failure
             */
            if (mCommonResponseListener != null) {
                mCommonResponseListener.onSuccess(null, responseString);
            }
        }

    }
}
